from flask_sqlalchemy import SQLAlchemy
from __init__ import db, bcrypt


class BaseModel(db.Model):
    __abstract__ = True
    def delete(self):
        """软删除：将flag设置为0，标记为删除状态"""
        self.flag = 0
        db.session.commit()

    @classmethod
    def real_delete(cls, id):
        """物理删除：直接从数据库中删除用户"""
        record = cls.query.get(id)
        if record:
            db.session.delete(record)
            db.session.commit()

# 数据库模型
class User(BaseModel):
    id = db.Column(db.Integer, primary_key=True)
    username = db.Column(db.String(80), unique=True, nullable=False)
    password = db.Column(db.String(200), nullable=False)
    roles = db.relationship('Role', secondary='user_roles', backref=db.backref('users', lazy='dynamic'))

class Role(BaseModel):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True, nullable=False)
    permissions = db.relationship('Permission', secondary='role_permissions', backref=db.backref('roles', lazy='dynamic'))

class Permission(BaseModel):
    id = db.Column(db.Integer, primary_key=True)
    name = db.Column(db.String(80), unique=True, nullable=False)


# 关联表
user_roles = db.Table('user_roles',
    db.Column('user_id', db.Integer, db.ForeignKey('user.id'), primary_key=True),
    db.Column('role_id', db.Integer, db.ForeignKey('role.id'), primary_key=True)
)

role_permissions = db.Table('role_permissions',
    db.Column('role_id', db.Integer, db.ForeignKey('role.id'), primary_key=True),
    db.Column('permission_id', db.Integer, db.ForeignKey('permission.id'), primary_key=True)
)


    # 初始化数据库
def init_db():
    db.create_all()
    admin_role = Role(name='admin')
    user_role = Role(name='user')

    read_perm = Permission(name='read')
    write_perm = Permission(name='write')

    admin_role.permissions.extend([read_perm, write_perm])
    user_role.permissions.append(read_perm)

    admin_user = User(username='admin', password=bcrypt.generate_password_hash('admin').decode('utf-8'))
    admin_user.roles.append(admin_role)

    db.session.add_all([admin_role, user_role, read_perm, write_perm, admin_user])
    db.session.commit()